package main

import (
	"fmt"
	"log"
	"net"
	"time"
)

func main() {
	conn, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4zero, Port: 9002})
	if err != nil {
		log.Fatal(err)
	}

	log.Printf("local address: <%s>\n", conn.LocalAddr().String())

	peers := make([]net.UDPAddr, 0, 2)
	data := make([]byte, 1024)

	for {
		n, remoteAddr, err := conn.ReadFromUDP(data)
		if err != nil {
			fmt.Printf("err duraing read: %s", err)
		}

		log.Printf("remote address: <%s> %s\n", remoteAddr.String(), data[:n])
		peers = append(peers, *remoteAddr)

		if len(peers) == 2 {
			log.Printf("进行UDP打洞, 建立 %s <---> %s的连接\n", peers[0].String(), peers[1].String())
			_, err := conn.WriteToUDP([]byte(peers[1].String()), &peers[0])
			if err != nil {
				panic(err)
			}

			_, err = conn.WriteToUDP([]byte(peers[0].String()), &peers[1])
			if err != nil {
				panic(err)
			}

			time.Sleep(8 * time.Second)

			log.Println("中专服务器退出, 不影响peers的通信")
			return
		}

	}

}
